import { Component, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from '../../../../core/services/http/api.service';
import { GridConfigService } from 'app/core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { Events } from '../../../../core/services/events/Events';
import { ApesMessageService } from '../../../../shared/apes/message/index';
import { RenderOperatingButtonComponent } from '../../../../shared/ag-grid-ext/cell-renders/render-operating-button.component';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions } from '@ngx-formly/core';
import { ApesModalService } from '@shared/apes/modal';

@Component({
  selector: 'data-kanban-transfer',
  templateUrl: './data-kanban-transfer.component.html',
  styleUrls: ['./data-kanban-transfer.component.scss'],
})
export class DataKanbanTransferComponent implements OnInit, OnDestroy {

  /* 按钮相关 */
  buttonBar = [
    { style: 'primary', label: '确定', id: 'action_new', loading: false },
  ];

  ctx = { model: {} };
  site: any;

  /** formly 配置 **/
  form = new FormGroup({});
  formId = 'tms/dataKanban/dataKanbanTransferComponent';
  model: any = {};
  options: FormlyFormOptions = {};
  field: any[] = [
    {
      key: 'branchLineId',
      type: 'span',
      templateOptions: {
        label: '线路名称',
        divCol: '6',
      },
    },
    {
      key: 'chauffeurId',
      type: 'span',
      templateOptions: {
        label: '司机',
        divCol: '6',
        downFormatter: '\'[ \' + value.id + \' ]\' + \' \' + value.name',
        valueFormatter: '\'[ \' + value.id + \' ]\' + \' \' + value.name',
      },
    },
    {
      key: 'vehicleId',
      type: 'span',
      templateOptions: {
        label: '车辆',
        divCol: '6',
        downFormatter: 'value.vehicleNumber + \' \' +  \'[ \' + value.vehicleStatus.description + \' ]\'',
        valueFormatter: 'value.vehicleNumber + \' \' +  \'[ \' + value.vehicleStatus.description + \' ]\'',
      },
    },
    {
      key: 'totalWaybill',
      type: 'span',
      templateOptions: {
        label: '运单数',
        divCol: '6',
      },
    },
    {
      key: 'importantNote',
      type: 'important-note',
      templateOptions: {
        label: '重要提示',
        divCol: '24',
        col: '24',
        lblCol: '2',
        inputCol: '22',
        value: '请认真核对该派车单相关信息，一但保存，代表入库成功处于未指派任务中，谨慎核对！',
      },
    },
  ];

  /** Grid 相关 **/
  rowData: any[] = [];
  gridApi: any;
  gridOptions: GridOptions;
  columnDefs: any[] = [
    {
      headerName: '序号',
      editable: false,
      field: 'sort',
      pinned: 'left',
      suppressMenu: true,
      width: 75,
      headerCheckboxSelectionFilteredOnly: true,
      checkboxSelection: true,
      cellRenderer: this.sortCellRenderer,
    },
    { headerName: '运单', field: 'waybillId', width: 100 },
    { headerName: '来源单据', field: 'sourceBusinessKey', width: 100 },
    { headerName: '发货物流仓编码', field: 'deliveryAddress', width: 200, valueFormatter: 'value.id' },
    { headerName: '发货物理仓名称', field: 'deliveryAddress', width: 200, valueFormatter: 'value.name' },
    { headerName: '收货物流仓编码', field: 'shippingAddress', width: 200, valueFormatter: 'value.id' },
    { headerName: '收货物理仓名称', field: 'shippingAddress', width: 200, valueFormatter: 'value.name' },
    {
      headerName: '货物信息', field: 'dialogButton', width: 100,
      widget: 'dialogButton',
      cellRenderer: 'dialogButton',
      buttonList: [
        {
          'id': 'search',
          'name': '货物详情',
          'title': '货物详情信息',
          'hide': false,
          'disabled': false,
          'action': 'drawer',
          'width': '45vw',
          'formId': 'tms.waybill.findByWaybill',
          'api': 'tms.waybill.findByWaybill',
        },
      ],
    },
  ];
  frameworkComponents;  // 框架组件
  height: any = window.innerHeight - 325 + 'px';


  constructor(
    private event: Events,
    private gridConfigService: GridConfigService,
    private apiService: ApiService,
    private msg: ApesMessageService,
    private modalService: ApesModalService,
  ) {

  }

  ngOnInit() {
    this.frameworkComponents = {
      dialogButton: RenderOperatingButtonComponent,
    };
    this.event.subscribe(this.formId, () => {
      this.initData();
    });

    this.initData();
  }

  ngAfterViewInit() {

  }

  sortCellRenderer(params) {
    return params.rowIndex + 1;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_new') {
        // this.buttonBar[0].loading = true;
        this.clickDesignate();
      }
    }
  }

  initData() {
    let value = this.gridConfigService.getRouterData();

    if (value.hasOwnProperty('formId') && value['formId'] == this.formId) {

      this.model = {};
      this.rowData = [];

      let params = value.data;

      this.site = params['site'];
      let data = {
        carInformationId: params['carInformationId'],
        site: params['site'],
      };

      let api = 'tms.waybill.findTransitReceive';

      this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {

        if (body) {
          let totalWaybill = body['waybillList'].length;
          this.model = body;
          this.model['totalWaybill'] = totalWaybill;
          this.rowData = body['waybillList'];
        }
      });
    }
  }


  onGridReady(params) {
    this.gridApi = params.api;
    // this.gridColumnApi = params.columnApi;
    // this.setColumns();
    // params.api.sizeColumnsToFit();
    // 动态渲染,值存在渲染界面
    // if (this.formControl.value) {
    //   this._rowData = this.formControl.value;
    // }
  }

  // grid选中
  onSelectionChanged($event) {
    this.gridApi.forEachNode((node) => {
      let selected = node.isSelected();
      // 用于处理隐藏checkbox
      // if (node.data['hideSelected'] == true) {
      //   node.data['selected'] = false;
      // } else {
      node.data['selected'] = selected;
      // }
    });
  }

  clickDesignate() {
    let row = this.gridApi.getSelectedRows();

    if (row.length == 0) {
      this.msg.error('请选择运单');
      return;
    }
    let api = 'tms.waybill.transitReceive';

    let data = {
      site: this.site,
      assignedList: row,
    };

    this.modalService.confirm({
      apesTitle: '<b class="text-red">确认该批次派车单相关信息无误！</b>',
      apesContent: '一但保存，代表入库成功处于未指派任务中，谨慎核对',
      apesBodyStyle: { textAlign: 'center' },
      apesOkText: '确认',
      apesOkType: 'primary',
      apesOnOk: () => {
        this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {

          if (body) {
            this.initData();
          }
        });
      },
      apesCancelText: '取消',
      apesOnCancel: () => {
      },
    });


  }

  ngOnDestroy() {
    this.gridConfigService.resetRouterData();
    this.event.unsubscribe(this.formId);
  }

}
